package com.byt.framlib.commonutils;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

/**
 * 类名称：MySensorEventListener
 * 类描述：获取手机方向传感器的数值
 * 创建人: 钟文浩
 */
public class MySensorEventUtils implements SensorEventListener {
    private float mOri = 0;
    private float mDevicesDirection = 0f;
    private boolean mLandscape;
    private OnDevicesDirectionX mOnDevicesDirection = null;

    public void setLandscape(boolean mLandscape) {
        this.mLandscape = mLandscape;
    }

    public void setOnDevicesDirection(OnDevicesDirectionX mOnDevicesDirection) {
        this.mOnDevicesDirection = mOnDevicesDirection;
    }

    public MySensorEventUtils(boolean mLandscape) {
        this.mLandscape = mLandscape;
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
            float x = sensorEvent.values[SensorManager.DATA_X];
            float fixedX = x;
            if (mLandscape) {
                if (mOri < 0) {
                    fixedX -= 90;
                } else {
                    fixedX += 90;
                }
            }
            if (Math.abs(fixedX - mDevicesDirection) > 2) {
                mDevicesDirection = fixedX;
                if (mOnDevicesDirection != null) {
                    mOnDevicesDirection.onOrientationChangedX(mDevicesDirection);
                }
            }
        } else if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float x = sensorEvent.values[SensorManager.DATA_X];
            //            float y = sensorEvent.values[SensorManager.DATA_Y];
            //            float z = sensorEvent.values[SensorManager.DATA_Z];
            mOri = x;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    public interface OnDevicesDirectionX {
        void onOrientationChangedX(float mDevicesDirectionx);
    }
}